package Interfaces;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;

import calculator.auxiliary_I_Team;

import Auxiliary.Sequence_CondReact;
import Auxiliary.Sequence_Type;
import DataView.Action;
import DataView.EventInfo;
import DataView.Expr;
import DataView.ParameterInfo;
import Store.CondReact;
import Store.Event;
import Store.Parameter;
import Store.Type;

public class ECR_manageElement 
{
	JPanel container;
	ShowEventsAndCondReacts showEventCR;
	CampoTesto nome = new CampoTesto();
	CampoTesto parametro = new CampoTesto();
	JComboBox selectorParam;
	JPanel centerPanel;
	boolean modifica;
	Event originalElement;
	Sequence_Type avableTypes;
	Vector<Parameter> listaParametri;
	JTable tabAttr;
	JTable tabCoRe;
	JPanel pannelloConditionsReactions;
	Sequence_CondReact lista_CR;
	
	public JPanel show(ShowEventsAndCondReacts ecr, boolean modifica, Event original, Sequence_Type availableTypes) 
	{
		showEventCR = ecr;
		this.modifica=modifica;
		originalElement=original;
		avableTypes=availableTypes;
		
		container = new JPanel();
		container.setLayout(new BorderLayout());
		
		String  str="";
		if(modifica)
		{
			str=originalElement.getName();
			listaParametri = originalElement.getInfo().getParameters();
			lista_CR = originalElement.getInfo().getCondReact();
		}
		else 
		{
			listaParametri = new Vector<Parameter>();
			lista_CR = new Sequence_CondReact();
		}
		container.add(getIntestazione(str),BorderLayout.NORTH);
		
		container.add(getCenterArea(),BorderLayout.CENTER);
		container.add(getButtonArea(), BorderLayout.SOUTH);
		
		return container;
	}

	private JPanel getCenterArea() 
	{
		JPanel pannelloAttr = new JPanel();
		pannelloAttr.setLayout(new BorderLayout());
		JPanel buttonpanel = new JPanel();
		buttonpanel.setLayout(new GridLayout(1,5));
		
		selectorParam = new JComboBox ();
		int max = 0;
		if(avableTypes!=null) max=avableTypes.size();
		for(int i = 0 ; i<max ; i++)
			selectorParam.addItem(avableTypes.get(i).getName());
		
		JButton addAttribute = new JButton("Add Attribute");
		addAttribute.addActionListener(new ActionListener() 
		{
			@Override public void actionPerformed(ActionEvent arg0) 
			{
				Type t = avableTypes.trova((String)selectorParam.getSelectedItem());
				ParameterInfo info = new ParameterInfo();
				info.setInfo(parametro.getText(),t);
				Parameter a = new Parameter();
				a.mkElement(info);
				if(a.getName().length()==0)
				{
					showEventCR.showMessage("Insert name for atribute");
				}
				else{
				listaParametri.add(a);
				parametro.clear();
				refresh();
			}
				}
		});
		
		JButton delAttribute = new JButton("Delete Attribute");
		
		delAttribute.addActionListener(new ActionListener()
		{
			@Override public void actionPerformed(ActionEvent arg0) 
			{
				if(tabAttr.getSelectedRow()!=-1)
					listaParametri.remove(tabAttr.getSelectedRow());
				refresh();
			}
		});
		
		buttonpanel.add(parametro.crea("Insert Attribute Name"));
		buttonpanel.add(new JLabel("Type:",JLabel.RIGHT));
		buttonpanel.add(selectorParam);
		buttonpanel.add(addAttribute);
		buttonpanel.add(delAttribute);
		
		pannelloAttr.add(buttonpanel, BorderLayout.NORTH);
		pannelloAttr.add(getTableAtt(), BorderLayout.CENTER);
		
		centerPanel = new JPanel();
		centerPanel.setLayout(new BorderLayout());
		centerPanel.add(pannelloAttr, BorderLayout.NORTH);
		centerPanel.add(getCondReacArea(), BorderLayout.CENTER);
		
		return centerPanel;
	}

	private JPanel getIntestazione(String namestr) 
	{
		JPanel pannelloIntestazione = new JPanel();
		pannelloIntestazione.setLayout(new BorderLayout());
		JLabel label = new JLabel("New Event");
		if(modifica) label.setText("Modify Event");
		label.setFont(new Font("Tahoma", Font.BOLD, 18));
		pannelloIntestazione.add(label, BorderLayout.NORTH);
		if(modifica) 
		{
			nome.crea("Inserisci qui il nome");
			nome.setText(namestr);
			pannelloIntestazione.add(nome.get(), BorderLayout.CENTER);
		}
		else pannelloIntestazione.add(nome.crea("Insert Name"), BorderLayout.CENTER);
		
		pannelloIntestazione.add(label, BorderLayout.NORTH);
		pannelloIntestazione.add(new JLabel(" "), BorderLayout.SOUTH);
		
		return pannelloIntestazione;
	}
	
	@SuppressWarnings("serial")
	private JPanel getTableAtt() 
	{
		JPanel tabella = new JPanel();
		
		DefaultTableModel modelloRicerca = new DefaultTableModel();
		tabAttr = new JTable(modelloRicerca){public boolean isCellEditable(int rowIndex, int vColIndex){return false;}};
		modelloRicerca.addColumn("Attributes");
		tabAttr.setAutoCreateColumnsFromModel(false);								
		tabAttr.getTableHeader().setReorderingAllowed(false);
		tabAttr.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tabAttr.setFillsViewportHeight(true);
		
		int max = 0;
		if(listaParametri!=null)
			max=listaParametri.size();
		for (int i= 0; i<max; i++)
		{
			modelloRicerca.addRow(new Object[]{listaParametri.get(i).getDescription()});						
		}
		
		if(tabAttr.getRowCount()<4)
			modelloRicerca.setRowCount(3);
		
		tabella.setLayout(new BorderLayout());
		tabella.add(tabAttr.getTableHeader(), BorderLayout.NORTH);
		tabella.add(tabAttr, BorderLayout.CENTER);
		
		return tabella;
	}

	
	
	@SuppressWarnings("serial")
	private JPanel getCondReacArea() 
	{
		pannelloConditionsReactions = new JPanel();
		pannelloConditionsReactions.setLayout(new BorderLayout());
		JPanel aux = new JPanel();
		aux.setLayout(new GridLayout(1,3));
		JButton add = new JButton("Add Cond/React");
		add.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
	        {
				String[] CR=CR_manage.showInputDialog("Insert Condition/Reaction", "Insert Condition",  "Insert Reaction");
		        if(CR!=null)
		        {
		        	CondReact cr = new CondReact();
		        	cr.setCondReact(new Expr(CR[0]), new Action(CR[1]));
		        	lista_CR.add(cr);
		        	refresh();
		        }
	        }
		});
		   
		JButton del = new JButton("Delete Cond/React");
		del.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
	        {
		        if(tabCoRe.getSelectedRow()!=-1)
		        {			
					lista_CR.delete(tabCoRe.getSelectedRow());
		        	refresh();
		        }
	        }
		});
		
		JButton mod = new JButton("Modify Cond/React");
		mod.addActionListener(new ActionListener()
		{
			public void actionPerformed(ActionEvent e)
	        {
		        if(tabCoRe.getSelectedRow()!=-1)
		        {
					String[] CR=CR_manage.showInputDialog("Insert Condition/Reaction", lista_CR.get(tabCoRe.getSelectedRow()).getCond().getDescription(),lista_CR.get(tabCoRe.getSelectedRow()).getReact().getDescription());
					if(CR!=null)
					{
						
						lista_CR.get(tabCoRe.getSelectedRow()).setCondReact(new Expr(CR[0]), new Action(CR[1]));
			        	refresh();
					}
		        }
	        }
		});
		
		aux.add(add);
		aux.add(del);
		aux.add(mod);
		
		JPanel tabella = new JPanel();
		DefaultTableModel modelloRicerca = new DefaultTableModel();
		tabCoRe = new JTable(modelloRicerca){public boolean isCellEditable(int rowIndex, int vColIndex){return false;}@SuppressWarnings("unchecked")
		public Class getColumnClass(int columnIndex) {return String.class;}};
		modelloRicerca.addColumn("Condictions");
		modelloRicerca.addColumn("Reactions");		
		tabCoRe.setAutoCreateColumnsFromModel(false);								
		tabCoRe.getTableHeader().setReorderingAllowed(false);
		tabCoRe.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		tabCoRe.setFillsViewportHeight(true);
		int lines = 1;
		
		for (CondReact cr : lista_CR.getAll())
		{
			modelloRicerca.addRow(new Object[]{cr.getCond().getDescription(), cr.getReact().getDescription()});
			if(auxiliary_I_Team.getLineCount(cr.getCond().getDescription(),54)>lines || auxiliary_I_Team.getLineCount(cr.getReact().getDescription(),54)>lines)
				lines=(int)Math.max(auxiliary_I_Team.getLineCount(cr.getCond().getDescription(),54),auxiliary_I_Team.getLineCount(cr.getReact().getDescription(),54));
		}

		tabCoRe.setRowHeight(tabCoRe.getRowHeight() * lines);
		tabCoRe.setDefaultRenderer(String.class, new MultiLineCellRenderer());
		tabella.setLayout(new BorderLayout());
		tabella.add(tabCoRe.getTableHeader(), BorderLayout.NORTH);
			tabella.add(tabCoRe, BorderLayout.CENTER);

		
		pannelloConditionsReactions.add(aux, BorderLayout.NORTH);
		pannelloConditionsReactions.add(tabella, BorderLayout.CENTER);
		
		return pannelloConditionsReactions;
	}

	private JPanel getButtonArea() 
	{
		JPanel buttonPanel = new JPanel();
		JButton ok = new JButton("Save");
		JButton cancel = new JButton("Cancel");
		buttonPanel.setLayout(new GridLayout(1,2));
		buttonPanel.add(ok);
		buttonPanel.add(cancel);
		
		ok.addActionListener(new ActionListener() 
		{
			@SuppressWarnings("unchecked")
			@Override public void actionPerformed(ActionEvent arg0) 
			{
				EventInfo info = new EventInfo();
				info.setInfo(nome.getText(), (Vector<Parameter>)listaParametri.clone(), lista_CR.clone());
				if (info.getName().length()==0)
					showEventCR.showMessage("Insert name for Event");
				else{
					if(info.getCondReact().size()==0)
						showEventCR.showMessage("Insert a Cond/React");
					else{
					showEventCR.container.removeAll();
					if(modifica) showEventCR.updateEventCondReact.updEvent(originalElement, info);
					else showEventCR.updateEventCondReact.addEvent(info);
						}
					}
			}
		});
		
		cancel.addActionListener(new ActionListener() 
		{
			@Override public void actionPerformed(ActionEvent e) 
			{
				showEventCR.container.removeAll();
				showEventCR.showECR();
			}
		});
		
		return buttonPanel;
	}
	
	public void refresh()
	{
		centerPanel.removeAll();
		centerPanel.add(getCenterArea(), BorderLayout.CENTER);
		centerPanel.revalidate();
	}
}
